{% extends "base.html" %}

{% block title %}词汇测试 - 英语词汇量估算工具{% endblock %}

{% block content %}
<div class="row">
    <div class="col-lg-8 mx-auto">
        <div class="card">
            <div class="card-header">
                <h4 class="mb-0"><i class="fas fa-question-circle me-2"></i>交互式词汇测试</h4>
            </div>
            <div class="card-body">
                <div id="testInstructions" class="mb-4">
                    <h5>测试说明</h5>
                    <ul>
                        <li>系统将随机展示英语单词</li>
                        <li>请根据您是否认识该单词选择"认识"或"不认识"</li>
                        <li>测试包含不同难度的词汇，请诚实回答</li>
                        <li>建议测试50-100个单词以获得更准确的结果</li>
                    </ul>
                    
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="testCount" class="form-label">测试词汇数量</label>
                            <select id="testCount" class="form-select">
                                <option value="30">30个单词</option>
                                <option value="50" selected>50个单词</option>
                                <option value="80">80个单词</option>
                                <option value="100">100个单词</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label for="userLevel" class="form-label">预估英语水平</label>
                            <select id="userLevel" class="form-select">
                                <option value="">自动选择（推荐）</option>
                                <option value="beginner">初学者</option>
                                <option value="intermediate">中级</option>
                                <option value="advanced">高级</option>
                            </select>
                        </div>
                    </div>
                    
                    <button id="startTest" class="btn btn-primary">
                        <i class="fas fa-play me-2"></i>开始测试
                    </button>
                </div>
                
                <div id="testInterface" style="display: none;">
                    <div class="row mb-4">
                        <div class="col-md-6">
                            <div class="card">
                                <div class="card-body text-center">
                                    <h5>当前单词</h5>
                                    <h2 id="currentWord" class="text-primary mb-3">-</h2>
                                    <div class="progress mb-3">
                                        <div id="progressBar" class="progress-bar" role="progressbar" style="width: 0%"></div>
                                    </div>
                                    <p id="progressText">0 / 0</p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="card">
                                <div class="card-body text-center">
                                    <h5>选择答案</h5>
                                    <div class="d-grid gap-2">
                                        <button id="knownBtn" class="btn btn-success btn-lg">
                                            <i class="fas fa-check me-2"></i>认识
                                        </button>
                                        <button id="unknownBtn" class="btn btn-danger btn-lg">
                                            <i class="fas fa-times me-2"></i>不认识
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="text-center">
                        <button id="finishTest" class="btn btn-warning">
                            <i class="fas fa-stop me-2"></i>结束测试
                        </button>
                    </div>
                </div>
                
                <div id="testResult" style="display: none;">
                    <div class="card result-card">
                        <div class="card-body text-center">
                            <h4 class="mb-3">测试结果</h4>
                            <div class="row mb-4">
                                <div class="col-md-4">
                                    <h5>估算词汇量</h5>
                                    <h2 id="vocabularyEstimate" class="text-white">-</h2>
                                </div>
                                <div class="col-md-4">
                                    <h5>置信度</h5>
                                    <h2 id="confidence" class="text-white">-</h2>
                                </div>
                                <div class="col-md-4">
                                    <h5>英语等级</h5>
                                    <h2 id="levelDisplay" class="text-white">-</h2>
                                </div>
                            </div>
                            
                            <div id="levelDetails" class="mb-4" style="display: none;">
                                <div class="card">
                                    <div class="card-body">
                                        <h5 id="levelName" class="mb-2 text-dark"></h5>
                                        <p id="levelRange" class="text-muted mb-2"></p>
                                        <p id="levelDescription" class="text-dark mb-3"></p>
                                        <div id="levelFeatures" class="text-dark"></div>
                                        
                                        <!-- 详细分析信息 -->
                                        <div id="analysisDetails" class="mt-4" style="display: none;">
                                            <hr>
                                            <h6 class="text-dark mb-3">
                                                <i class="fas fa-chart-bar me-2"></i>详细分析
                                            </h6>
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <div class="mb-3">
                                                        <h6 class="text-muted">测试统计</h6>
                                                        <div class="d-flex justify-content-between">
                                                            <span>总单词数:</span>
                                                            <span id="totalWords" class="fw-bold">-</span>
                                                        </div>
                                                        <div class="d-flex justify-content-between">
                                                            <span>认识单词:</span>
                                                            <span id="knownWords" class="fw-bold text-success">-</span>
                                                        </div>
                                                        <div class="d-flex justify-content-between">
                                                            <span>不认识单词:</span>
                                                            <span id="unknownWords" class="fw-bold text-danger">-</span>
                                                        </div>
                                                        <div class="d-flex justify-content-between">
                                                            <span>准确率:</span>
                                                            <span id="accuracy" class="fw-bold text-primary">-</span>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="col-md-6">
                                                    <div class="mb-3">
                                                        <h6 class="text-muted">词汇特征</h6>
                                                        <div class="d-flex justify-content-between">
                                                            <span>平均词长:</span>
                                                            <span id="avgWordLength" class="fw-bold">-</span>
                                                        </div>
                                                        <div class="d-flex justify-content-between">
                                                            <span>平均词频排名:</span>
                                                            <span id="avgFrequencyRank" class="fw-bold">-</span>
                                                        </div>
                                                        <div class="d-flex justify-content-between">
                                                            <span>稀有词汇比例:</span>
                                                            <span id="rareWordsRatio" class="fw-bold">-</span>
                                                        </div>
                                                        <div class="d-flex justify-content-between">
                                                            <span>学术词汇比例:</span>
                                                            <span id="academicRatio" class="fw-bold">-</span>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <!-- 级别分布 -->
                                            <div class="mb-3">
                                                <h6 class="text-muted">词汇级别分布</h6>
                                                <div id="levelDistribution" class="row">
                                                    <!-- 级别分布将在这里动态生成 -->
                                                </div>
                                            </div>
                                            
                                            <!-- 复杂度分析 -->
                                            <div class="mb-3">
                                                <h6 class="text-muted">复杂度分析</h6>
                                                <div class="d-flex justify-content-between">
                                                    <span>综合复杂度得分:</span>
                                                    <span id="complexityScore" class="fw-bold text-warning">-</span>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <!-- 四级六级成绩对比 -->
                                        <div id="scoreComparison" class="mt-4" style="display: none;">
                                            <hr>
                                            <h6 class="text-dark mb-3">
                                                <i class="fas fa-chart-line me-2"></i>成绩对比分析
                                            </h6>
                                            <div class="row">
                                                <div class="col-md-4">
                                                    <div class="text-center">
                                                        <h6 class="text-muted">四级成绩</h6>
                                                        <span id="cet4ScoreDisplay" class="badge bg-primary fs-5">未设置</span>
                                                    </div>
                                                </div>
                                                <div class="col-md-4">
                                                    <div class="text-center">
                                                        <h6 class="text-muted">六级成绩</h6>
                                                        <span id="cet6ScoreDisplay" class="badge bg-success fs-5">未设置</span>
                                                    </div>
                                                </div>
                                                <div class="col-md-4">
                                                    <div class="text-center">
                                                        <h6 class="text-muted">词汇量估算</h6>
                                                        <span id="vocabEstimateDisplay" class="badge bg-info fs-5">-</span>
                                                    </div>
                                                </div>
                                            </div>
                                            <div id="scoreAnalysis" class="mt-3 p-3 bg-light rounded">
                                                <small class="text-muted">
                                                    <i class="fas fa-info-circle me-1"></i>
                                                    成绩对比分析将在这里显示
                                                </small>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <p id="resultMessage" class="mt-3"></p>
                            <div class="mt-4">
                                <button id="newTest" class="btn btn-light me-2">
                                    <i class="fas fa-redo me-2"></i>重新测试
                                </button>
                                <button id="viewHistory" class="btn btn-light">
                                    <i class="fas fa-history me-2"></i>查看历史
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div id="alertContainer"></div>
{% endblock %}

{% block extra_js %}
<script>
$(document).ready(function() {
    let testWords = [];
    let currentIndex = 0;
    let testResults = [];
    
    $('#startTest').click(function() {
        // 获取用户选择的测试参数
        const testCount = parseInt($('#testCount').val()) || 50;
        const userLevel = $('#userLevel').val() || null;
        
        // 显示加载状态
        $('#startTest').prop('disabled', true).text('正在生成测试词汇...');
        
        // 显示难度策略信息
        let strategyInfo = '';
        if (userLevel) {
            strategyInfo = `使用用户选择的难度: ${userLevel}`;
        } else {
            strategyInfo = '使用自动选择策略（优先四六级成绩，其次平衡分布）';
        }
        
        // 从服务器获取随机测试词汇
        $.ajax({
            url: '/api/get_test_words',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({
                count: testCount,
                user_level: userLevel
            }),
            success: function(response) {
                if (response.success) {
                    testWords = response.words;
                    currentIndex = 0;
                    testResults = [];
                    
                    // 显示难度策略信息
                    showAlert(`词汇生成成功！${strategyInfo}`, 'info');
                    
                    $('#testInstructions').hide();
                    $('#testInterface').show();
                    updateTestInterface();
                } else {
                    showAlert('获取测试词汇失败: ' + response.error, 'danger');
                }
            },
            error: function() {
                showAlert('网络错误，请重试', 'danger');
            },
            complete: function() {
                $('#startTest').prop('disabled', false).text('开始测试');
            }
        });
    });
    
    $('#knownBtn').click(function() {
        recordAnswer(true);
    });
    
    $('#unknownBtn').click(function() {
        recordAnswer(false);
    });
    
    $('#finishTest').click(function() {
        if (testResults.length < 10) {
            showAlert('建议至少测试10个单词以获得更准确的结果', 'warning');
            return;
        }
        finishTest();
    });
    
    $('#newTest').click(function() {
        $('#testResult').hide();
        $('#testInstructions').show();
    });
    
    $('#viewHistory').click(function() {
        window.location.href = '{{ url_for("dashboard") }}';
    });
    
    function updateTestInterface() {
        if (currentIndex < testWords.length) {
            $('#currentWord').text(testWords[currentIndex]);
            $('#progressText').text(`${currentIndex + 1} / ${testWords.length}`);
            const progress = ((currentIndex + 1) / testWords.length) * 100;
            $('#progressBar').css('width', progress + '%');
        }
    }
    
    function recordAnswer(known) {
        testResults.push({
            word: testWords[currentIndex],
            known: known
        });
        
        currentIndex++;
        
        if (currentIndex >= testWords.length) {
            finishTest();
        } else {
            updateTestInterface();
        }
    }
    
    function finishTest() {
        $('#testInterface').hide();
        $('#testResult').show();
        
        // 发送测试结果到服务器
        $.ajax({
            url: '/api/estimate_vocabulary',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({
                test_data: testResults
            }),
            success: function(response) {
                if (response.success) {
                    // 显示词汇量
                    $('#vocabularyEstimate').text(response.vocabulary_size.toLocaleString());
                    
                    // 显示置信度
                    $('#confidence').text((response.confidence * 100).toFixed(1) + '%');
                    
                    // 显示等级信息
                    const level = response.level;
                    $('#levelDisplay').text(level.display);
                    $('#levelName').text(level.info.name);
                    $('#levelRange').text('词汇量范围: ' + level.info.range);
                    $('#levelDescription').text(level.info.description);
                    
                    // 显示等级特征
                    let featuresHtml = '<h6>能力特征:</h6><ul class="list-unstyled">';
                    level.info.features.forEach(function(feature) {
                        featuresHtml += '<li><i class="fas fa-check text-success me-2"></i>' + feature + '</li>';
                    });
                    featuresHtml += '</ul>';
                    $('#levelFeatures').html(featuresHtml);
                    
                    // 显示等级详情
                    $('#levelDetails').show();
                    
                    // 显示详细分析信息
                    if (response.analysis) {
                        displayAnalysisDetails(response.analysis);
                    }
                    
                    // 设置等级颜色
                    const levelColors = {
                        'secondary': 'text-secondary',
                        'success': 'text-success', 
                        'info': 'text-info',
                        'warning': 'text-warning',
                        'primary': 'text-primary',
                        'danger': 'text-danger',
                        'dark': 'text-dark',
                        'purple': 'text-purple'
                    };
                    
                    const colorClass = levelColors[level.color] || 'text-primary';
                    $('#levelDisplay').removeClass().addClass('text-white ' + colorClass);
                    $('#levelName').removeClass().addClass(colorClass);
                    
                    // 显示结果消息
                    $('#resultMessage').text(`恭喜！您的英语词汇量达到 ${level.info.name}，词汇量约为 ${response.vocabulary_size.toLocaleString()} 个单词。`);
                    
                    // 加载并显示成绩对比
                    loadScoreComparison(response.vocabulary_size);
                } else {
                    showAlert(response.message, 'danger');
                }
            },
            error: function() {
                showAlert('测试结果提交失败，请稍后重试', 'danger');
            }
        });
    }
    
    // 加载成绩对比
    function loadScoreComparison(vocabularySize) {
        $.ajax({
            url: '/api/get_user_scores',
            method: 'GET',
            success: function(response) {
                if (response.success) {
                    displayScoreComparison(response.cet4_score, response.cet6_score, vocabularySize);
                }
            },
            error: function() {
                // 如果获取成绩失败，仍然显示词汇量估算
                displayScoreComparison(null, null, vocabularySize);
            }
        });
    }
    
    // 显示成绩对比
    function displayScoreComparison(cet4Score, cet6Score, vocabularySize) {
        // 更新成绩显示
        if (cet4Score !== null) {
            $('#cet4ScoreDisplay').text(cet4Score).removeClass('bg-secondary').addClass('bg-primary');
        } else {
            $('#cet4ScoreDisplay').text('未设置').removeClass('bg-primary').addClass('bg-secondary');
        }
        
        if (cet6Score !== null) {
            $('#cet6ScoreDisplay').text(cet6Score).removeClass('bg-secondary').addClass('bg-success');
        } else {
            $('#cet6ScoreDisplay').text('未设置').removeClass('bg-success').addClass('bg-secondary');
        }
        
        // 更新词汇量显示
        $('#vocabEstimateDisplay').text(vocabularySize.toLocaleString());
        
        // 生成分析报告
        let analysis = generateScoreAnalysis(cet4Score, cet6Score, vocabularySize);
        $('#scoreAnalysis').html(analysis);
        
        // 显示成绩对比区域
        $('#scoreComparison').show();
    }
    
    // 生成成绩分析报告
    function generateScoreAnalysis(cet4Score, cet6Score, vocabularySize) {
        let analysis = '<div class="text-dark">';
        
        // 词汇量与四级成绩对比
        if (cet4Score !== null) {
            let cet4Vocab = estimateVocabFromCET4(cet4Score);
            let diff = Math.abs(vocabularySize - cet4Vocab);
            let percentage = Math.round((diff / cet4Vocab) * 100);
            
            analysis += `<p><strong>四级成绩对比:</strong> 您的四级成绩 ${cet4Score} 分对应约 ${cet4Vocab.toLocaleString()} 词汇量，`;
            analysis += `与当前估算相差 ${diff.toLocaleString()} 词 (${percentage}%)</p>`;
        }
        
        // 词汇量与六级成绩对比
        if (cet6Score !== null) {
            let cet6Vocab = estimateVocabFromCET6(cet6Score);
            let diff = Math.abs(vocabularySize - cet6Vocab);
            let percentage = Math.round((diff / cet6Vocab) * 100);
            
            analysis += `<p><strong>六级成绩对比:</strong> 您的六级成绩 ${cet6Score} 分对应约 ${cet6Vocab.toLocaleString()} 词汇量，`;
            analysis += `与当前估算相差 ${diff.toLocaleString()} 词 (${percentage}%)</p>`;
        }
        
        // 总体建议
        if (cet4Score !== null || cet6Score !== null) {
            analysis += `<p><strong>建议:</strong> `;
            if (vocabularySize < 12000) {
                analysis += '建议继续扩充词汇量，为四级考试做准备。';
            } else if (vocabularySize < 18000) {
                analysis += '词汇量已达到四级水平，可以考虑准备六级考试。';
            } else if (vocabularySize < 25000) {
                analysis += '词汇量已达到六级水平，可以尝试更高级别的英语考试。';
            } else {
                analysis += '词汇量非常优秀，已达到专业英语水平。';
            }
            analysis += '</p>';
        } else {
            analysis += '<p><strong>建议:</strong> 设置您的四级和六级成绩，可以获得更详细的分析报告。</p>';
        }
        
        analysis += '</div>';
        return analysis;
    }
    
    // 根据四级成绩估算词汇量
    function estimateVocabFromCET4(score) {
        if (score < 425) return 8000;  // 未通过
        if (score < 500) return 12000; // 及格
        if (score < 550) return 15000; // 良好
        if (score < 600) return 17000; // 优秀
        return 18000; // 满分
    }
    
    // 根据六级成绩估算词汇量
    function estimateVocabFromCET6(score) {
        if (score < 425) return 15000; // 未通过
        if (score < 500) return 18000; // 及格
        if (score < 550) return 21000; // 良好
        if (score < 600) return 23000; // 优秀
        return 25000; // 满分
    }
    
    // 显示详细分析信息
    function displayAnalysisDetails(analysis) {
        // 显示测试统计
        $('#totalWords').text(analysis.total_words);
        $('#knownWords').text(analysis.known_words);
        $('#unknownWords').text(analysis.unknown_words);
        $('#accuracy').text((analysis.accuracy * 100).toFixed(1) + '%');
        
        // 显示词汇特征
        $('#avgWordLength').text(analysis.avg_word_length);
        $('#avgFrequencyRank').text(analysis.avg_frequency_rank.toLocaleString());
        $('#rareWordsRatio').text((analysis.rare_words_ratio * 100).toFixed(1) + '%');
        $('#academicRatio').text((analysis.academic_ratio * 100).toFixed(1) + '%');
        
        // 显示复杂度得分
        $('#complexityScore').text(analysis.complexity_score);
        
        // 显示级别分布
        displayLevelDistribution(analysis.level_distribution);
        
        // 显示分析详情
        $('#analysisDetails').show();
    }
    
    // 显示级别分布
    function displayLevelDistribution(levelDistribution) {
        const levelNames = {
            'primary': '小学',
            'middle': '初中', 
            'high': '高中',
            'cet4': '四级',
            'cet6': '六级',
            'advanced': '高级'
        };
        
        const levelColors = {
            'primary': 'bg-secondary',
            'middle': 'bg-info',
            'high': 'bg-success',
            'cet4': 'bg-warning',
            'cet6': 'bg-primary',
            'advanced': 'bg-danger'
        };
        
        let html = '';
        for (const [level, ratio] of Object.entries(levelDistribution)) {
            const percentage = (ratio * 100).toFixed(1);
            const colorClass = levelColors[level] || 'bg-secondary';
            const levelName = levelNames[level] || level;
            
            html += `
                <div class="col-md-4 mb-2">
                    <div class="d-flex justify-content-between align-items-center">
                        <span class="badge ${colorClass} me-2">${levelName}</span>
                        <span class="fw-bold">${percentage}%</span>
                    </div>
                    <div class="progress mt-1" style="height: 6px;">
                        <div class="progress-bar ${colorClass}" style="width: ${percentage}%"></div>
                    </div>
                </div>
            `;
        }
        
        $('#levelDistribution').html(html);
    }
    
    function showAlert(message, type) {
        const alertHtml = `
            <div class="alert alert-${type} alert-dismissible fade show" role="alert">
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        `;
        $('#alertContainer').html(alertHtml);
    }
});
</script>
{% endblock %} 